#! /usr/bin/env python
#coding=utf-8

import os
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "../"))
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "../../"))

import loader
import graphviz

from utils import ResterHelper
from utils import ResterStringBuilder

class ComponentRest(loader.Component, ResterStringBuilder):
	def getStr(self, xargs=None, keys=None):
		ordered_keys = ("id", "subsystem", "name", "size", "bss_size", "data_size", "modules", "deps_internal", "deps", "dependedBy")
		return ResterStringBuilder.getStr(self, xargs, ordered_keys)

	def queryFieldStr(self, type, xargs):
		if graphviz.requestingGraphviz(xargs):
			productMgr = xargs["_product_mgr"]
			builder = productMgr.getGraphVizBuilder()
			return builder.buildGraph(self, "components", xargs)
		vals = self[type]
		return ResterHelper.build_array_content(vals, xargs)

class ComponentDepRest(loader.ComponentDependency, ResterStringBuilder):
	def getStr(self, xargs=None, keys=None):
		ordered_keys = ("id", "caller.name", "callee.name", "calls")
		return ResterStringBuilder.getStr(self, xargs, ordered_keys)

class ComponentRestMgr(loader.ComponentMgr):
	def __init__(self, product):
		loader.ComponentMgr.__init__(self, product.getMgr("modules"), ComponentRest, ComponentDepRest)

	def doRestRequest(self, id, mod, xargs):
		mCmdMap = {
			'deps':self._dbGetDeps,
			'fields': self._dbQueryFields
		}
		return mCmdMap[mod](id, xargs)

	def _dbQueryFields(self, id, xargs):
		component = self.find_by_id(int(id))
		return component.queryFieldStr(xargs["type"], xargs)

	def _dbGetDeps(self, id, xargs):
		if xargs["type"] == "dep":
			dep = self.get_dep_by_id(int(id))
			vals = dep["calls"]
		else:
			vals = self.find_by_id(int(id))[xargs["type"]]
		return ResterHelper.build_array_content(vals, xargs)

if __name__ == "__main__":
	import products

	product_mgr = products.Products()
	prod = product_mgr.get_all()[0]
	prod.load_db()

	mgr = ComponentRestMgr(prod)
